package com.iv.durian.cloud.facade.support;

import com.iv.durian.cloud.RandomCode;
import com.iv.durian.cloud.facade.RandomCodeFacade;
import com.iv.durian.cloud.service.RandomCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class RandomCodeFacadeImpl implements RandomCodeFacade {

    @Autowired
    private RandomCodeService randomCodeService;

    @Override
    public String generateCode(String key) {
        Assert.notNull(key,"key is required");
        RandomCode randomCode = randomCodeService.get(key);
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        if (randomCode == null){
            randomCode = new RandomCode();
            randomCode.setKey(key);
            randomCode.setCode(verifyCode);
            randomCodeService.add(randomCode);
        }else {
            randomCodeService.update(key,verifyCode);
        }

        return verifyCode;
    }

    @Override
    public boolean verifyCode(String key, String code) {
        RandomCode randomCode = randomCodeService.get(key);
        if (randomCode == null){
            return false;
        }
        if (randomCode.getCreateTime().getTime() - new Date().getTime() > TimeUnit.MINUTES.toMillis(10)){
            return false;
        }
        return StringUtils.equals(code,randomCode.getCode());
    }
}
